<template>
  <view class="page-detail">
        <view class="page-detail__adv pd-v-24 pd-h-24" v-if="message.length" @click="toMessageList">
            <view class="flex flex-center" >
                <image src="@/static/msg.png" mode="widthFix" style="width:40rpx;" class="mr-r-16"></image>
                <view class="flex-1 overflow-h" id="textWrap">
                    <text class="color-white font26 lh-36 nowrap position-r" :style="{left:moveLeft+'px'}"  id="text">{{message[0].title}}</text>
                </view>
            </view>
            
        </view>

        <view class="page-detail__body mr-v-24 pd-b-200">
            <scroll-view class="imgs mr-h-20" scroll-x>
                <view class="flex flex-center" v-if="storeDetail?.imageList?.length">
                    <image v-for="(item,index) in storeDetail.imageList" :key="'item'+index" class="img-item mr-r-16 border8" :src="getFileUrl(item)" />
                </view>
            </scroll-view>

            <view class="pd-v-24 pd-t-32 pd-b-20 bg-white border8">
                <view class="font32 lh-44 bold color-default">
                    {{storeDetail.name}}
                </view>
                <view class="mr-t-16 font24 lh-36 color-info">
                    {{storeDetail.splitAddress}}
                </view>

                <view class="flex flex-center flex-j-between mr-t-32">
                    <view class="flex flex-center font26 lh-36 color-default" @click="collect">
                        <u-icon name="star-fill" color="#35BE65" size="24" v-if="storeDetail.isCollect == 1"></u-icon>
                        <u-icon name="star" color="#999" size="24" v-else></u-icon>
                        收藏
                    </view>
                      
                    
                    <view class="flex flex-center">
                            
                        <view class="mr-r-16" >
                            <u-button type="primary" shape="circle" color="#272636" @click="repairPhone">
                              <image src="@/static/phone.png" style="width:24rpx;" mode="widthFix" class="mr-r-4"></image>
                              报修充电桩
                            </u-button>
                        </view>
                          
                        <u-button type="primary" shape="circle" color="#35BE65" @click="openLocation">
                          <image src="@/static/phone.png" style="width:24rpx;" mode="widthFix" class="mr-r-4"></image>
                          开始导航
                        </u-button>
                          
                    </view>
                      
                </view>
                  
                  
                  
            </view>


            <view class="mr-t-20">
                <image class="" src="@/sub_user/static/3.gif" @click="phone" style="width:100%;" mode="widthFix" />
            </view>

            <view class="mr-t-20 pd-t-40 bg-white border8">
                <view class="flex flex-center pd-v-24">
                    <view class="flex-1 font28 lh-28 color-default bold">
                        充电桩信息
                    </view>

                    <view class="font24 lh-28 color-info">
                        {{isFreeCount}}/{{socketList.length ? socketList[tabIndex].socketVoList.length : 0}}
                    </view>
                      
                      
                </view>

                <view class="border-b pd-b-6 mr-v-24">
                    <u-tabs :list="socketList" keyName="deviceName" @change="tabChange" lineColor="#35BE65" lineWidth="36"></u-tabs>
                </view>
                

                <view class="flex flex-center charge-list pd-t-32 pd-b-44">
                    <template v-for="(item,index) in socketList"  >
                        <view class="flex flex-wrap  full-w"  v-if="tabIndex == index" :key="'index'+index">
                            <view class="charge-list__item flex-shrink flex flex-ver flex-center flex-j-center pd-v-24 mr-h-24 box" v-for="(socketItem,socketIndex) in item.socketVoList" :key="'socketIndex'+socketIndex"  @click="goCharge(item,socketItem)">
                                
                                <image class="" v-if="socketItem.status == 'FREE'" src="@/static/charge_active.png" style="width:48rpx;" mode="widthFix" />
                                <image class="" v-else src="@/static/charge.png" style="width:48rpx;" mode="widthFix" />
                                <view class="font24 lh-34 color-default mr-t-8 line1 full-w txt-center">
                                    {{socketItem.port}}
                                </view>

                                <view class="status font20 lh-28 txt-center pd-h-4 mr-t-12" :class="socketItem.status == 'FREE' ? 'active' : ''">
                                    {{  socketItem.status == 'FREE' ? '空闲' : 
                                        socketItem.status == 'WORKING' ? '使用中' : 
                                        socketItem.status == 'BREAKDOWN' ? '故障' : ''}}
                                </view>
                                    
                            </view>
                        </view>
                    </template>
                    
                        
                </view>
                  
                  
            </view>


            <view class="mr-t-20 pd-t-42 pd-v-24 pd-b-76  border8 bg-white">
                <view class="font28 lh-28 color-default bold">
                    永久计费策略
                </view>

                <view class="flex mr-t-34">
                    <view class="font26 lh-28 color-info mr-r-28">
                        计费类型
                    </view>

                    <view class="flex-1">
                        <view class="font26 lh-28 color-default">
                            电量计费
                        </view>
                          
                    </view>
                      
                      
                </view>
                  
                
                

                <view class="flex mr-t-34">
                    <view class="font26 lh-28 color-info mr-r-28">
                        计费策略
                    </view>

                    <view class="flex-1">
                        <view class="font26 lh-28 color-default">
                            按电量计费
                        </view>
                        
                        <view class="flex mr-t-20">
                            <view class="flex-1 font24 lh-28 color-info">
                                00:00-24:00
                            </view>
                            <view class="font24 lh-28 color-info ">
                                {{storeDetail.chargeFee}}元/度
                            </view>
                                
                        </view>

                        
                        <view class="font26 lh-28 color-default mr-t-34">
                            服务费：按功率计费
                        </view>
                        
                        <view class="flex  mr-t-20" v-for="(item,index) in storeDetail.serviceChargeList" :key="'cost'+index">
                            <view class="flex-1 font24 lh-28 color-info">
                                {{item.startPower}}-{{item.endPower}}瓦
                            </view>
                            <view class="font24 lh-28 color-info ">
                               {{item.price}}元/小时
                            </view>
                                
                        </view>
                          
                          
                    </view>
                      
                      
                </view>
            </view>


            <view class="footer pd-v-24 pd-t-30 bg-white position-f full-w box flex flex-start">
                <view class="flex-1 mr-r-20 flex flex-end">
                    <view class="price font52 lh-52 color-default flex flex-end">
                        <view class="font32 lh-32">
                            ￥
                        </view>
                          {{storeDetail.chargeFee}}
                    </view>
                    <view class="flex-1 unit font28 lh-28 color-default">
                        /度+服务费
                    </view>
                        
                </view>
                <view>
                    
                    <u-button type="primary" shape="circle" color="#35BE65" text="扫码充电" @click="scanCode"></u-button>
                </view>
                  
                  
            </view>
              
              
              
              
              
        </view>
          
          
  </view>
</template>

<script setup>

import { useStore } from '@/store/index.js';
import { getStoreQueryById,getSocketListByStoreId,notificationFormList } from "@/api/index/index.js";

import { computed, ref, onMounted, reactive,defineProps } from "vue";
import { onLoad, onShow, onUnload } from '@dcloudio/uni-app';
import { fileUrl } from '@/utils/index.js'
import { collectAdd, collectCancel } from '@/api/user.js'

const props = defineProps({
    id: {
        type: String,
        default: ''
    }
});

const store = useStore();
const constList = ref([
    {range:'0-200瓦',cost:'0.53元/小时'},
    {range:'200-300瓦',cost:'0.62元/小时'},
    {range:'300-500瓦',cost:'0.72元/小时'},
    {range:'500-600瓦',cost:'1.11元/小时'},
    {range:'600-800瓦',cost:'1.51元/小时'},
    {range:'800-1500瓦',cost:'1.69元/小时'}]);
const storeDetail = ref({})
const socketList = ref([])
const tabIndex = ref(0)
const message = ref([])
const textWrap = ref(null);
const text = ref(null);
const timer = ref(null)
const moveLeft = ref(0)
const maxMoveLeft = ref(0)


onShow(() => {
  socketListByStoreId()
})

onLoad(() => {
    storeQueryById()
    socketListByStoreId()
    getNotificationFormList()
    animation()
});


onUnload(() => {
    clearInterval(timer.value)
});

const animation = () => {
    let textWrap = uni.createSelectorQuery().select("#textWrap")
    let text = uni.createSelectorQuery().select("#text")
    textWrap.boundingClientRect(textWrapData => {
        console.log(textWrapData,'textWrapData')
        text.boundingClientRect(textData => {
            console.log(textData,'textData')
            if (textData.width > textWrapData.width) {
                timer.value = setInterval(() => {
                    maxMoveLeft.value = -(textData.width+10);
                    moveLeft.value-=1

                    if(moveLeft.value <= maxMoveLeft.value) {
                        moveLeft.value = -maxMoveLeft.value
                    }
                }, 16);
            }
        }).exec()
    }).exec()
}


const getNotificationFormList = () => {
    notificationFormList({
        pageSize:10,
        pageNum:1
    }).then(res => {
        if(res.code == 200){
            message.value = res.rows
        }
    })
}

const tabChange = (item,index) => {
    console.log(index,item);
    tabIndex.value = index
}

const isFreeCount = computed(() => {
    console.log(socketList.value[tabIndex.value])
    if(!socketList.value[tabIndex.value]) {
        return 0
    } 
    return socketList.value[tabIndex.value].socketVoList.filter(item => {
        
            return item.status == 'FREE'
        
    }).length
})


const socketListByStoreId = () => {
    getSocketListByStoreId({storeId:props.id}).then(res => {
        console.log(res,'resssssss')
        if(res.code == 200) {
            socketList.value = res.data
        }
    })
}



const getFileUrl = (avatar) => {
    return fileUrl(avatar)
}


const storeQueryById = () => {
    getStoreQueryById({id:props.id}).then(res => {
        console.log(res,'resssssss')
        if(res.code == 200) {
            if(res.data.image) {
                res.data.imageList = res.data.image.split(',')
            } else {
                res.data.imageList = []
            }
            storeDetail.value = res.data
        }
    })
}

const collect = () => {
    if(storeDetail.value.isCollect == 1) {
        collectCancel({storeId:props.id}).then(res => {
            console.log(res,'resssssss')
            if(res.code == 200) {
                storeDetail.value.isCollect = 0
                uni.showToast({
                    title:'取消收藏成功',
                    icon:'none'
                })
            } else {
                uni.showToast({
                    title:res.msg,
                    icon:'none'
                })

            }
        })
    } else {
        collectAdd({storeId:props.id}).then(res => {
            if(res.code == 200) {
                storeDetail.value.isCollect = 1
                uni.showToast({
                    title:'收藏成功',
                    icon:'none'
                })
            } else {
                uni.showToast({
                    title:res.msg,
                    icon:'none'
                })
            }
        })
    }
}

const goCharge = (item,socketItem) => {
    // uni.navigateTo({
    //     url: '/sub_user/pages/chargeSelect/chargeSelect?deviceId='+item.deviceId
    // })
    if(socketItem.status == 'FREE') {
        
        uni.navigateTo({
            url: '/sub_user/pages/chargePayment/chargePayment?deviceNumber='+item.deviceNumber+'&port='+socketItem.port+'&deviceId='+item.deviceId+'&storeId='+props.id
        })
    } else if(socketItem.status == 'WORKING') {
        uni.showToast({
            title:'该插座正在使用中',
            icon:'none'
        })
    } else if(socketItem.status == 'BREAKDOWN') {
        uni.showToast({
            title:'该插座故障，请尽快联系客服',
            icon:'none'
        })
    }
}

const repairPhone = () => {
// #ifndef MP-WEIXIN
    uni.makePhoneCall({
        phoneNumber: storeDetail.value.repairPhone
    });
// #endif

// #ifdef MP-WEIXIN
    wx.openOfficialAccountArticle({
        url:'https://mp.weixin.qq.com/s/nafApeayNAyZccnejlbKmg'
    })
// #endif
}

const toMessageList = () => {
    uni.navigateTo({
        url: '/sub_user/pages/messageList/messageList'
    })
}

const scanCode = () => {
    uni.scanCode({
        success: function (res) {
            console.log(res);
            let url = res.result;
            let equipmentReg = /equipment\/([^\/]+)/
            let socketReg = /socket\/([^\/]+)/
            let equipmentMatch = url.match(equipmentReg)
            let socketMatch = url.match(socketReg)
            if(equipmentMatch && equipmentMatch[1] &&  socketMatch && socketMatch[1]) {
                if(store?.user.token) {
                    uni.navigateTo({
                        url: '/sub_user/pages/chargePayment/chargePayment?deviceNumber='+equipmentMatch[1]+'&port='+socketMatch[1]
                    })
                } else {
                    uni.navigateTo({
                        url: '/sub_user/pages/login/login'
                    })
                }
            } else if(equipmentMatch && equipmentMatch[1] && !socketMatch) {
                if(store?.user.token) {
                    uni.navigateTo({
                        url: '/sub_user/pages/chargeSelect/chargeSelect?deviceNumber='+equipmentMatch[1]
                    })
                } else {
                    uni.navigateTo({
                        url: '/sub_user/pages/login/login'
                    })
                }
            } else {
                uni.showToast({
                    title:'请扫描正确的二维码',
                    icon:'none'
                })
            }
        }
    });
}



const phone = () => {
    uni.makePhoneCall({
        phoneNumber: store?.common?.platformInfo.platformCustomerServicePhone
    });
}


const openLocation = () => {
    console.log(123)
    uni.openLocation({
        latitude: Number(storeDetail.value.location.split(',')[1]),
        longitude: Number(storeDetail.value.location.split(',')[0]),
        name: storeDetail.value.name,
        address: storeDetail.value.detailedAddress,
        success: function (res) {
            console.log(res);
        },
        fail: function (res) {
            console.log(res);
        },
    })
}
</script>

<style lang="scss" scoped>
.page-detail {
    background: #F5F5F5;
    min-height:100vh;
    .page-detail__adv {
        background:#35BE65;

    }  

    .imgs {
        .img-item {
            width:400rpx;
            height:240rpx;
            flex-shrink: 0;

        }
    }

    .border-b {
        border-bottom:1px solid #EEEEEE;
    }


    .charge-list {
        .charge-list__item {
            width:20%;
            
            .status {
                width:80rpx;
                color:rgba(51, 52, 54, 0.4);
                border-radius: 18rpx;
                background: #F0F0F0;


                &.active {
                    color:#2B9951;
                    background: rgba(53, 190, 101, 0.2);
                }
            }

        }
    }

    .footer {
        box-shadow: 0px -1px 2px 0px rgba(0,0,0,0.05);
        left:0;
        bottom:0;
        height: 176rpx;

        .price {
            color:rgba(43, 153, 81, 1);
        }
    }


    .scroll-content {
        white-space: nowrap;
        animation: scroll 5s linear infinite;
        -webkit-animation: scroll 5s linear infinite;
    }
} 

@keyframes scroll {
    0% { left: 0 }
    100% { left:-100%; }
}
</style>
